package com.ys.everydaynews.view

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.ys.everydaynews.R

class MyCheckBox @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    private var isChecked = false
    private val isSelected = R.mipmap.check_select
    private val isUnSelected = R.mipmap.check_unselect
    private val img: ImageView
    private val text: TextView
    private var mClickableSpanText: ClickableSpanText? = null

    init {
        val inflate = View.inflate(context, R.layout.mycheckbox, this)
        img = inflate.findViewById(R.id.image)
        text = inflate.findViewById(R.id.text)
    }

    fun changeState() {
        isChecked = !isChecked
        if (isChecked) {
            img.setImageResource(isSelected)
        } else {
            img.setImageResource(isUnSelected)
        }
    }

    fun isChecked(): Boolean = isChecked

    fun initSpan(spanIds:Int) {
        val span = SpannableString(resources.getString(spanIds))
        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                mClickableSpanText?.onClick(1)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = ContextCompat.getColor(context, R.color.c_222222)
                ds.isUnderlineText = false
            }
        }, 7, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                mClickableSpanText?.onClick(2)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = ContextCompat.getColor(context, R.color.c_222222)
                ds.isUnderlineText = false
            }
        }, 15, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        text.movementMethod = LinkMovementMethod.getInstance()
        text.highlightColor = Color.TRANSPARENT
        text.text = span
    }

    interface ClickableSpanText {
        fun onClick(type: Int)
    }

    fun setClickableSpanText(mClickableSpanText: ClickableSpanText) {
        this.mClickableSpanText = mClickableSpanText
    }

    fun isShow(isShow:Boolean){
        if (isShow){
            img.visibility= VISIBLE
        }else{
            img.visibility= GONE
        }
    }
}